﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    Layout = null;
}
<style>
    .texts-input {
        margin-top: 20px; /* 每个文本框下方留出20px的间距 */
        width: 100%;
    }
    
    /* 表格样式优化 */
    .layui-table {
        table-layout: fixed; /* 固定表格布局 */
        width: 100%;
    }
    
    .layui-table th,
    .layui-table td {
        height: 45px; /* 固定行高 */
        line-height: 45px; /* 行高一致 */
        vertical-align: middle; /* 垂直居中 */
        text-align: center; /* 水平居中 */
        padding: 5px 8px; /* 内边距 */
        white-space: nowrap; /* 不换行 */
        overflow: hidden; /* 超出隐藏 */
        text-overflow: ellipsis; /* 超出显示省略号 */
        border: 1px solid #e6e6e6; /* 边框 */
    }
    
    .layui-table thead th {
        background-color: #f2f2f2; /* 表头背景色 */
        font-weight: bold; /* 表头加粗 */
        height: 50px; /* 表头高度 */
        line-height: 50px; /* 表头行高 */
    }
    
    .layui-table tbody tr {
        height: 45px; /* 表格行固定高度 */
    }
    
    .layui-table tbody tr:hover {
        background-color: #f8f8f8; /* 鼠标悬停效果 */
    }
    
    /* 操作按钮样式 */
    .layui-table .layui-btn {
        margin: 0 2px; /* 按钮间距 */
        padding: 2px 8px; /* 按钮内边距 */
        height: 28px; /* 按钮高度 */
        line-height: 24px; /* 按钮行高 */
    }
    
    /* 状态徽章样式 */
    .layui-badge {
        display: inline-block;
        padding: 2px 8px;
        border-radius: 3px;
        font-size: 12px;
        min-width: 50px;
        text-align: center;
    }
    
    /* 表格列宽度控制 */
    .layui-table th:nth-child(1) { width: 60px; text-align: center; } /* 复选框 */
    .layui-table th:nth-child(2) { width: 8%; } /* 出货检验单编号 */
    .layui-table th:nth-child(3) { width: 8%; } /* 验单名称 */
    .layui-table th:nth-child(4) { width: 8%; } /* 客户名称 */
    .layui-table th:nth-child(5) { width: 6%; } /* 批次号 */
    .layui-table th:nth-child(6) { width: 7%; } /* 产品编码 */
    .layui-table th:nth-child(7) { width: 8%; } /* 产品名称 */
    .layui-table th:nth-child(8) { width: 6%; } /* 规格型号 */
    .layui-table th:nth-child(9) { width: 4%; } /* 单位 */
    .layui-table th:nth-child(10) { width: 5%; } /* 发货数量 */
    .layui-table th:nth-child(11) { width: 5%; } /* 检测数量 */
    .layui-table th:nth-child(12) { width: 5%; } /* 不合格数 */
    .layui-table th:nth-child(13) { width: 6%; } /* 检测结果 */
    .layui-table th:nth-child(14) { width: 6%; } /* 出货日期 */
    .layui-table th:nth-child(15) { width: 6%; } /* 检测日期 */
    .layui-table th:nth-child(16) { width: 6%; } /* 检测人员 */
    .layui-table th:nth-child(17) { width: 6%; } /* 单据状态 */
    .layui-table th:nth-child(18) { width: 10%; } /* 操作 */
    
    /* 数值列右对齐 */
    .layui-table td:nth-child(10),
    .layui-table td:nth-child(11),
    .layui-table td:nth-child(12) {
        text-align: right;
        padding-right: 15px;
    }

    /* 复选框列居中 */
    .layui-table td:nth-child(1) {
        text-align: center;
    }
    
    /* 行更新动画效果 */
    .layui-table tbody tr.layui-bg-green {
        background-color: #e8f5e8 !important;
        transition: background-color 0.3s ease;
    }
    
    .layui-table tbody tr.layui-bg-green td {
        background-color: transparent !important;
    }
</style>
<link href="~/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
<body>
    <div class="search-box">
        <div class="layui-form">
            <div class="layui-form-item texts-input" style="margin-bottom: 0;">
                <label class="layui-form-label">检测单编号:</label>
                <div class="layui-input-inline">
                    <input type="text" id="outgoingCode" name="outgoingCode" placeholder="请输入检测单编号" autocomplete="off" class="layui-input">
                </div>
                <label class="layui-form-label">客户名称:</label>
                <div class="layui-input-inline">
                    <input type="text" id="customerName" name="customerName" placeholder="请输入客户名称" autocomplete="off" class="layui-input">
                </div>
                <label class="layui-form-label">批次号:</label>
                <div class="layui-input-inline">
                    <input type="text" id="batch" name="batch" placeholder="请输入批次号" autocomplete="off" class="layui-input">
                </div>
                <label class="layui-form-label">产品物料编码:</label>
                <div class="layui-input-inline">
                    <input type="text" id="productCode" name="productCode" placeholder="请输入产品物料编码" autocomplete="off" class="layui-input">
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">产品物料名称:</label>
                    <div class="layui-input-inline">
                        <input type="text" id="productName" name="productName" placeholder="请输入产品物料名称" autocomplete="off" class="layui-input">
                    </div>
                    <label class="layui-form-label">记录人:</label>
                    <div class="layui-input-inline">
                        <input type="text" id="testingPerson" name="testingPerson" placeholder="请输入记录人" autocomplete="off" class="layui-input">
                    </div>
                    <label class="layui-form-label">检测结果:</label>
                    <div class="layui-input-inline">
                        <select id="testingResult" name="testingResult">
                            <option value="">请选择检测结果</option>
                            <option value="合格">合格</option>
                            <option value="不合格">不合格</option>
                            <option value="待检测">待检测</option>
                        </select>
                    </div>
                    <button class="layui-btn layui-bg-blue" lay-submit lay-filter="searchForm">
                        <i class="layui-icon layui-icon-search"></i> 搜索
                    </button>
                    <button type="reset" class="layui-btn layui-btn-primary" onclick="resetForm()">
                        <i class="layui-icon layui-icon-refresh"></i> 重置
                    </button>
                    <button type="button" class="layui-btn layui-bg-blue" onclick="addInspectionRecord()"><i class="layui-icon layui-icon-addition"></i>新增</button>
                    <button type="button" class="layui-btn layui-bg-red" onclick="batchDeleteRecords()"><i class="layui-icon &#xe640; layui-icon-delete"></i>批量删除</button>
                </div>
            </div>
        </div>
    </div>
    <div class="page-container">
        @Html.AntiForgeryToken()
        <table class="layui-table" lay-size="sm" lay-even>
            <thead>
                <tr>
                    <th width="60px">
                        <input type="checkbox" id="selectAll" lay-filter="selectAll" title="全选/全不选">
                    </th>
                    <th>出货检验单编号</th>
                    <th>检验单名称</th>
                    <th>客户名称</th>
                    <th>批次号</th>
                    <th>产品编码</th>
                    <th>产品名称</th>
                    <th>规格型号</th>
                    <th>单位</th>
                    <th>发货数量</th>
                    <th>检测数量</th>
                    <th>不合格数</th>
                    <th>检测结果</th>
                    <th>出货日期</th>
                    <th>检测日期</th>
                    <th>检测人员</th>
                    <th>单据状态</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="tb">
            </tbody>
        </table>
        <div id="pagination"></div>
    </div>
</body>
<script src="~/scripts/jquery-3.4.1.min.js"></script>
<script src="~/scripts/layui-v2.5.6/layui/layui.js"></script>
<script>
layui.use(['form', 'laydate', 'element'], function() {
    var form = layui.form;
    var laydate = layui.laydate;
    var element = layui.element;
    
    // 表单渲染
    form.render();
    
    // 页面加载时加载数据
    loadInspectionData();
    
    // 搜索表单提交
    form.on('submit(searchForm)', function(data) {
        searchInspectionData();
        return false;
    });

    // 全选/全不选功能
    form.on('checkbox(selectAll)', function(data) {
        var checked = data.elem.checked;
        $('.record-checkbox').each(function() {
            this.checked = checked;
        });
        form.render('checkbox');
    });

    // 单个复选框变化时检查全选状态
    form.on('checkbox(recordCheck)', function(data) {
        updateSelectAllStatus();
    });
});

// 新增检验记录
function addInspectionRecord() {
    layer.open({
        type: 2,
        title: '新增出货检验记录',
        shadeClose: true,
        shade: 0.8,
        maxmin: true,
        area: ['1500px', '1000px'],
        content: '/OutgoingInspection/AddInspectionView'
    });
}

// 搜索检验数据
function searchInspectionData() {
    var searchParams = {};
    
    // 根据正确的ID获取各个搜索框的值
    var outgoingCode = $('#outgoingCode').val().trim();
    var customerName = $('#customerName').val().trim();
    var batch = $('#batch').val().trim();
    var productCode = $('#productCode').val().trim();
    var productName = $('#productName').val().trim();
    var testingPerson = $('#testingPerson').val().trim();
    var testingResult = $('#testingResult').val();
    
    if (outgoingCode) searchParams.OutgoingCode = outgoingCode;
    if (customerName) searchParams.CustomerName = customerName;
    if (batch) searchParams.Batch = batch;
    if (productCode) searchParams.ProductCode = productCode;
    if (productName) searchParams.ProductName = productName;
    if (testingPerson) searchParams.TestingPerson = testingPerson;
    if (testingResult) searchParams.TestingResult = testingResult;
    
    console.log('搜索参数:', searchParams);  // 调试信息
    loadInspectionData(searchParams);
}

// 加载检验数据
function loadInspectionData(searchParams = {}) {
    var loadingIndex = layer.load(1, {
        shade: [0.3, '#000']
    });
    
    $.ajax({
        url: '/OutgoingInspection/GetOutgoingInspection',
        type: 'GET',
        data: searchParams,
        success: function(result) {
            layer.close(loadingIndex);
            
            // 调试：打印返回的数据
            console.log('后端返回的完整数据:', result);
            if (result && result.length > 0) {
                console.log('第一条记录的详细数据:', result[0]);
                console.log('第一条记录的所有属性:');
                for (var key in result[0]) {
                    console.log(key + ':', result[0][key]);
                }
                // 特别检查ID字段
                console.log('ID字段检查:');
                console.log('item.id:', result[0].id);
                console.log('item.Id:', result[0].Id);
                console.log('实际使用的ID:', result[0].id || result[0].Id);
            }
            
            if (result && Array.isArray(result)) {
                renderTableData(result);
                layer.msg('查询成功，共找到 ' + result.length + ' 条记录', {icon: 1, time: 1500});
            } else {
                renderTableData([]);
                layer.msg('未找到相关数据', {icon: 0, time: 1500});
            }
        },
        error: function(xhr, status, error) {
            layer.close(loadingIndex);
            console.error('查询出错:', xhr.responseText);
            renderTableData([]);
            layer.msg('查询失败，请稍后重试', {icon: 2, time: 2000});
        }
    });
}

// 渲染表格数据
function renderTableData(data) {
    var tbody = $('#tb');
    tbody.empty();
    
    if (!data || data.length === 0) {
        tbody.append('<tr><td colspan="18" style="text-align: center; color: #999;">暂无数据</td></tr>');
        return;
    }
    
    // 前端排序：按ID升序排列，保持数据顺序稳定
    data.sort(function(a, b) {
        var idA = parseInt(a.id || a.Id || 0);
        var idB = parseInt(b.id || b.Id || 0);
        return idA - idB; // 升序排列
    });
    
    $.each(data, function(index, item) {
        var stateValue = item.state !== undefined ? item.state : item.State;
        var statusText = getStatusText(stateValue);
        var statusClass = getStatusClass(stateValue);
        
        var row = `
            <tr data-id="${item.id || item.Id}">
                <td>
                    <input type="checkbox" class="record-checkbox" lay-filter="recordCheck" value="${item.id || item.Id}" title="">
                </td>
                <td title="${safeValue(item.outgoingCode)}">${safeValue(item.outgoingCode)}</td>
                <td title="${safeValue(item.outgoingName)}">${safeValue(item.outgoingName)}</td>
                <td title="${safeValue(item.customerName)}">${safeValue(item.customerName)}</td>
                <td title="${safeValue(item.batch)}">${safeValue(item.batch)}</td>
                <td title="${safeValue(item.productCode)}">${safeValue(item.productCode)}</td>
                <td title="${safeValue(item.productName)}">${safeValue(item.productName)}</td>
                <td title="${safeValue(item.specifications)}">${safeValue(item.specifications)}</td>
                <td title="${safeValue(item.unitt)}">${safeValue(item.unitt)}</td>
                <td title="${safeValue(item.sendNum)}">${safeValue(item.sendNum)}</td>
                <td title="${safeValue(item.testingNum)}">${safeValue(item.testingNum)}</td>
                <td title="${safeValue(item.unqualifiedNum)}">${safeValue(item.unqualifiedNum)}</td>
                <td title="${safeValue(item.testingResult)}">${safeValue(item.testingResult)}</td>
                <td title="${formatDate(item.shipmentDate)}">${formatDate(item.shipmentDate)}</td>
                <td title="${formatDate(item.testingDate)}">${formatDate(item.testingDate)}</td>
                <td title="${safeValue(item.testingPerson)}">${safeValue(item.testingPerson)}</td>
                <td><span class="layui-badge ${statusClass}" title="${statusText}">${statusText}</span></td>
                <td>
                    <button class="layui-btn layui-btn-xs layui-btn-normal" onclick="editRecord(${item.id || item.Id})" title="编辑记录">编辑</button>
                    <button class="layui-btn layui-btn-xs layui-btn-danger" onclick="deleteRecord(${item.id || item.Id})" title="删除记录">删除</button>
                </td>
            </tr>
        `;
        tbody.append(row);
    });
    
    // 重新渲染复选框
    layui.form.render('checkbox');
    // 更新全选状态
    updateSelectAllStatus();
}

// 获取状态文本
function getStatusText(state) {
    switch(state) {
        case 0: return '草稿';
        case 1: return '已确认';
        case 2: return '已完成';
        default: return '未知';
    }
}

// 获取状态样式类
function getStatusClass(state) {
    switch(state) {
        case 0: return 'layui-bg-gray';
        case 1: return 'layui-bg-blue';
        case 2: return 'layui-bg-green';
        default: return 'layui-bg-gray';
    }
}

// 获取检测结果样式类
function getResultClass(result) {
    switch(result) {
        case '合格': return 'layui-bg-green';
        case '不合格': return 'layui-bg-red';
        case '待检测': return 'layui-bg-orange';
        default: return 'layui-bg-gray';
    }
}

// 安全值处理函数
function safeValue(value) {
    if (value === null || value === undefined || value === '') {
        return '-';
    }
    return String(value).trim() || '-';
}

// 格式化日期
function formatDate(dateString) {
    if (!dateString) return '-';
    var date = new Date(dateString);
    if (isNaN(date.getTime())) return '-';
    
    var year = date.getFullYear();
    var month = String(date.getMonth() + 1).padStart(2, '0');
    var day = String(date.getDate()).padStart(2, '0');
    
    return `${year}-${month}-${day}`;
}

// 查看详情
function viewDetail(id) {
    layer.msg('查看详情功能开发中...', {icon: 1});
}

// 编辑记录
function editRecord(id) {
    console.log('编辑记录 - 接收到的ID:', id);
    
    if (!id || id === 'undefined') {
        layer.msg('记录ID无效，无法编辑', {icon: 2, time: 2000});
        return;
    }
    
    layer.open({
        type: 2,
        title: '编辑出货检验记录',
        shadeClose: true,
        shade: 0.8,
        maxmin: true,
        area: ['1500px', '1000px'],
        content: '/OutgoingInspection/UpdateInspectionView?id=' + id,
        success: function(layero, index) {
            // 传递更新回调函数到父窗口，供子窗口调用
            window.updateCallback = function(updatedData) {
                console.log('编辑回调 - 接收到的更新数据:', updatedData);
                updateTableRow(id, updatedData);
                layer.close(index);
            };
        }
    });
}

// 更新表格中的特定行数据
function updateTableRow(id, updatedData) {
    console.log('更新表格行数据 - ID:', id, '数据:', updatedData);
    console.log('状态值检查 - state:', updatedData.state, 'State:', updatedData.State);
    
    // 找到对应的表格行
    var $targetRow = $('#tb tr[data-id="' + id + '"]');
    
    if ($targetRow.length === 0) {
        // 如果通过data-id找不到，尝试通过onclick属性查找
        $('#tb tr').each(function() {
            var $row = $(this);
            var $editBtn = $row.find('button[onclick*="editRecord(' + id + ')"]');
            if ($editBtn.length > 0) {
                $targetRow = $row;
                return false; // 跳出循环
            }
        });
    }
    
    if (!$targetRow || $targetRow.length === 0) {
        console.log('未找到对应的表格行，重新加载数据');
        loadInspectionData();
        return;
    }
    
    // 更新行数据 - 修复状态获取逻辑
    var stateValue = updatedData.state !== undefined ? updatedData.state : updatedData.State;
    console.log('最终使用的状态值:', stateValue);
    var statusText = getStatusText(stateValue);
    var statusClass = getStatusClass(stateValue);
    
    var cells = $targetRow.find('td');
    
    // 更新各列数据（按表格列顺序，注意第0列是复选框，数据从第1列开始）
    cells.eq(1).text(safeValue(updatedData.outgoingCode || updatedData.OutgoingCode)).attr('title', safeValue(updatedData.outgoingCode || updatedData.OutgoingCode));
    cells.eq(2).text(safeValue(updatedData.outgoingName || updatedData.OutgoingName)).attr('title', safeValue(updatedData.outgoingName || updatedData.OutgoingName));
    cells.eq(3).text(safeValue(updatedData.customerName || updatedData.CustomerName)).attr('title', safeValue(updatedData.customerName || updatedData.CustomerName));
    cells.eq(4).text(safeValue(updatedData.batch || updatedData.Batch)).attr('title', safeValue(updatedData.batch || updatedData.Batch));
    cells.eq(5).text(safeValue(updatedData.productCode || updatedData.ProductCode)).attr('title', safeValue(updatedData.productCode || updatedData.ProductCode));
    cells.eq(6).text(safeValue(updatedData.productName || updatedData.ProductName)).attr('title', safeValue(updatedData.productName || updatedData.ProductName));
    cells.eq(7).text(safeValue(updatedData.specifications || updatedData.Specifications)).attr('title', safeValue(updatedData.specifications || updatedData.Specifications));
    cells.eq(8).text(safeValue(updatedData.unitt || updatedData.Unitt)).attr('title', safeValue(updatedData.unitt || updatedData.Unitt));
    cells.eq(9).text(safeValue(updatedData.sendNum || updatedData.SendNum)).attr('title', safeValue(updatedData.sendNum || updatedData.SendNum));
    cells.eq(10).text(safeValue(updatedData.testingNum || updatedData.TestingNum)).attr('title', safeValue(updatedData.testingNum || updatedData.TestingNum));
    cells.eq(11).text(safeValue(updatedData.unqualifiedNum || updatedData.UnqualifiedNum)).attr('title', safeValue(updatedData.unqualifiedNum || updatedData.UnqualifiedNum));
    cells.eq(12).text(safeValue(updatedData.testingResult || updatedData.TestingResult)).attr('title', safeValue(updatedData.testingResult || updatedData.TestingResult));
    cells.eq(13).text(formatDate(updatedData.shipmentDate || updatedData.ShipmentDate)).attr('title', formatDate(updatedData.shipmentDate || updatedData.ShipmentDate));
    cells.eq(14).text(formatDate(updatedData.testingDate || updatedData.TestingDate)).attr('title', formatDate(updatedData.testingDate || updatedData.TestingDate));
    cells.eq(15).text(safeValue(updatedData.testingPerson || updatedData.TestingPerson)).attr('title', safeValue(updatedData.testingPerson || updatedData.TestingPerson));
    
    // 更新状态列（第17列，索引16）
    cells.eq(16).html('<span class="layui-badge ' + statusClass + '" title="' + statusText + '">' + statusText + '</span>');
    
    // 添加行闪烁效果提示更新成功
    $targetRow.addClass('layui-bg-green');
    setTimeout(function() {
        $targetRow.removeClass('layui-bg-green');
    }, 2000);
    
    // 滚动到更新的行
    if ($targetRow.length > 0) {
        $('html, body').animate({
            scrollTop: $targetRow.offset().top - 100
        }, 500);
    }
    
    layer.msg('数据更新成功');
}

// 删除记录
function deleteRecord(id) {
    layer.confirm('确定要删除这条记录吗？', {
        icon: 3,
        title: '确认删除'
    }, function(index) {
        var loadingIndex = layer.load(1);
        
        $.ajax({
            url: '/OutgoingInspection/DeleteOutgoingInspection',
            type: 'POST',
            data: { id: id },
            headers: {
                'RequestVerificationToken': $('input[name="__RequestVerificationToken"]').val()
            },
            success: function(result) {
                layer.close(loadingIndex);
                layer.close(index);
                layer.msg('删除成功', {icon: 1, time: 1500});
                loadInspectionData();
            },
            error: function(xhr, status, error) {
                layer.close(loadingIndex);
                layer.close(index);
                console.error('删除出错:', xhr.responseText);
                layer.msg('删除失败，请稍后重试', {icon: 2});
            }
        });
    });
}

// 重置表单
function resetForm() {
    document.querySelector('.layui-form').reset();
    layui.form.render();
    loadInspectionData();
}

// 更新全选状态
function updateSelectAllStatus() {
    var totalCheckboxes = $('.record-checkbox').length;
    var checkedCheckboxes = $('.record-checkbox:checked').length;
    var selectAllCheckbox = $('#selectAll')[0];
    
    if (totalCheckboxes === 0) {
        selectAllCheckbox.checked = false;
        selectAllCheckbox.indeterminate = false;
    } else if (checkedCheckboxes === 0) {
        selectAllCheckbox.checked = false;
        selectAllCheckbox.indeterminate = false;
    } else if (checkedCheckboxes === totalCheckboxes) {
        selectAllCheckbox.checked = true;
        selectAllCheckbox.indeterminate = false;
    } else {
        selectAllCheckbox.checked = false;
        selectAllCheckbox.indeterminate = true;
    }
}

// 批量删除记录
function batchDeleteRecords() {
    // 获取选中的记录ID
    var selectedIds = [];
    $('.record-checkbox:checked').each(function() {
        selectedIds.push(parseInt($(this).val()));
    });
    
    if (selectedIds.length === 0) {
        layer.msg('请选择要删除的记录', {icon: 0, time: 2000});
        return;
    }
    
    // 友好提示确认删除
    layer.confirm('确定要删除选中的 ' + selectedIds.length + ' 条记录吗？<br><span style="color: red;">此操作不可撤销！</span>', {
        icon: 3,
        title: '批量删除确认',
        area: ['400px', '200px'],
        btn: ['确定删除', '取消']
    }, function(index) {
        // 执行批量删除
        var loadingIndex = layer.load(1, {
            shade: [0.3, '#000']
        });
        
        // 获取CSRF令牌
        var token = $('input[name="__RequestVerificationToken"]').val();
        
        console.log('批量删除 - 选中的IDs:', selectedIds);
        console.log('批量删除 - CSRF令牌:', token);
        
        $.ajax({
            url: '/OutgoingInspection/BatchDeleteOutgoingInspection',
            type: 'POST',
            data: { ids: selectedIds.join(',') },
            headers: {
                'RequestVerificationToken': token
            },
            success: function(result) {
                layer.close(loadingIndex);
                layer.close(index);
                
                console.log('批量删除响应:', result);
                
                if (result.success) {
                    layer.msg(result.message + ' (' + selectedIds.length + ' 条记录)', {icon: 1, time: 2000});
                    // 重新加载数据
                    loadInspectionData();
                    // 重置全选状态
                    $('#selectAll')[0].checked = false;
                    updateSelectAllStatus();
                    layui.form.render('checkbox');
                } else {
                    layer.msg(result.message || '删除失败', {icon: 2, time: 2000});
                }
            },
            error: function(xhr, status, error) {
                layer.close(loadingIndex);
                layer.close(index);
                console.error('批量删除出错:', xhr.responseText);
                layer.msg('删除失败，请联系管理员', {icon: 2, time: 2000});
            }
        });
    });
}

// 获取选中的记录数量
function getSelectedCount() {
    return $('.record-checkbox:checked').length;
}
</script>